package com.fw.ui.view.common.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.springframework.context.annotation.Scope;

import com.fw.ui.view.common.TwinListSelectPanel;
import com.fw.ui.view.event.AbstractTextChangeListener;
import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.ui.Component;

@org.springframework.stereotype.Component
@Scope(SCOPE_PROTOTYPE)
public class TwinListSelectPanelCurrentSelectedTextChangeListener extends AbstractTextChangeListener {

    private static final long serialVersionUID = -3606297278704167297L;

    private TwinListSelectPanel twinListSelectPanel;

    @Override
    public void change(TextChangeEvent event) throws Exception {
	String text = event.getText();
	if (text != null && text.trim().length() > 0) {
	    Map<Object, String> newMap = new HashMap<Object, String>();
	    Set<Object> keySet = twinListSelectPanel.getCurrentSelectedMap().keySet();
	    Iterator<Object> keyIterator = keySet.iterator();
	    while (keyIterator.hasNext()) {
		Object key = keyIterator.next();
		String str = twinListSelectPanel.getCurrentSelectedMap().get(key);
		if (str.toLowerCase().startsWith(text.toLowerCase())) {
		    newMap.put(key, str);
		}
	    }
	    twinListSelectPanel.setListSelectData(newMap, twinListSelectPanel.getSelectCurrent());
	} else {
	    twinListSelectPanel.setListSelectData(twinListSelectPanel.getCurrentSelectedMap(), twinListSelectPanel.getSelectCurrent());
	}
    }

    @Override
    public void setBasedComponent(Component basedComponent) {
	this.twinListSelectPanel = (TwinListSelectPanel) basedComponent;
    }

    @Override
    public boolean validate(TextChangeEvent event) throws Exception {
	return true;
    }

}
